package com.shugl.study.leetcode;

import java.util.HashMap;
import java.util.Map;

/**
 * Description 获取通过key获取数量
 *
 * @author Shugl
 * @version 1.0
 * @since 2021/5/28 10:37
 */
public class WordsFrequency {
    Map<String, Integer> map;

    public WordsFrequency(String[] book) {
        map = new HashMap<>(book.length);
        for (String k : book) {
            map.getOrDefault(k, 0);
            Integer num = map.get(k);
            if (num == null) {
                map.put(k, 1);
            } else {
                map.put(k, num + 1);
            }
        }
    }

    public static void main(String[] args) {
        WordsFrequency wordsFrequency = new WordsFrequency(new String[]{"i", "have", "an", "apple", "he", "have", "a", "pen"});
        System.out.println(wordsFrequency.get("you"));
        System.out.println(wordsFrequency.get("have"));
    }

    public int get(String word) {
        if (map == null) {
            return 0;
        }
        return map.get(word) == null ? 0 : map.get(word);
    }
}
